import * as THREE from 'three';
import { CSS3DRenderer } from 'three/examples/jsm/renderers/CSS3DRenderer.js';
import * as TWEEN from 'three/examples/jsm/libs/tween.module.js';
import { useEffect } from 'react';

const useThreejsManage = (inputRef: any, initPage: () => void) => {
  let camera: any = null;
  let scene: any = null;
  let renderer: any = null;
  const width = window.innerWidth;
  const height = window.innerHeight;

  function initCamera() {
    camera = new THREE.PerspectiveCamera(40, window.innerWidth / window.innerHeight, 1, 10000);
    camera.position.z = 3000;
    scene = new THREE.Scene();
  }

  function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
    render();
  }

  function animate() {
    initPage && initPage();
    requestAnimationFrame(animate);
    TWEEN.update();
  }

  function render() {
    renderer.render(scene, camera);
  }

  function initThreejs() {
    initCamera();
    renderer = new CSS3DRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    window.addEventListener('resize', onWindowResize);
  }
  function initRenderer() {
    inputRef.current.appendChild(renderer.domElement);
  }
  initThreejs();
  useEffect(() => {
    animate();
  }, []);

  return { initRenderer, renderer, scene, camera, width, height, render, animate };
};

export { useThreejsManage };
